package com.daon.service.impl;

import com.daon.common.Const;
import com.daon.common.ServerResponse;
import com.daon.dao.SysRoleUserMapper;
import com.daon.dao.SysUserMapper;
import com.daon.param.SysUserParam;
import com.daon.pojo.*;
import com.daon.service.ISysUserService;
import com.daon.util.IpUtil;
import com.daon.util.MD5Util;
import com.daon.vo.SysUserVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author 1daon
 * @EMAIL 532418116@qq.com
 * @Version 创建时间：2019/3/21 15:36 PM
 * @Modified By
 */
@Service("iSysUserService")
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Override
    public ServerResponse login(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String Verify   = request.getParameter("verify");
        String remember = request.getParameter("remember");
        if(StringUtils.isBlank(Verify)) return ServerResponse.createByErrorMessage("验证码不能为空");
        LocalDateTime expireTime = (LocalDateTime) session.getAttribute(Const.VerifySession.VERIFY_EXPIRE_TIME);
        if(expireTime == null) return ServerResponse.createByErrorMessage("非法操作");
        if(LocalDateTime.now().isAfter(expireTime)){
            session.removeAttribute(Const.VerifySession.VERIFY_CODE);
            return ServerResponse.createByErrorMessage("验证码已过期");
        }
        String verifyCode = session.getAttribute(Const.VerifySession.VERIFY_CODE).toString();
        if(!Verify.equalsIgnoreCase(verifyCode)){
            return ServerResponse.createByErrorMessage("验证码不正确");
        }
        //检测用户是否存在
        int resultCount = sysUserMapper.checkUsername(username);
        if(resultCount <= 0) return ServerResponse.createByErrorMessage("用户名不存在");
        //检测密码是否正确
        SysUser user = sysUserMapper.selectLogin(username, MD5Util.getMD5(password));
        if(user == null) return ServerResponse.createByErrorMessage("密码错误");
        if(user.getUserStatus() != 1) return ServerResponse.createByErrorMessage("用户已被禁用，请联系管理员！");
        updateCurrentUserIp(user, IpUtil.getRemoteIp(request));
        user.setUserPassword(StringUtils.EMPTY);
        session.setAttribute(Const.CURRENT_USER_INFO, user);
        session.removeAttribute(Const.VerifySession.VERIFY_CODE);
        session.removeAttribute(Const.VerifySession.VERIFY_EXPIRE_TIME);
        if(StringUtils.isBlank(remember)){
            //如果s是null或s是0~n个空格组成的字符串（""、"  "…）返回true
            //如果没有选中记住密码,则将已记住密码的cookie失效.即有效时间设为0
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals(username)){
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }else{
            //创建cookie对象
            Cookie ck = new Cookie(username, password);
            //设置Cookie有效时间,单位为妙
            ck.setMaxAge(60*60*24);
            //设置Cookie的有效范围,/为全部路径
            ck.setPath("/");
            response.addCookie(ck);
        }
        return ServerResponse.createBySuccessMessage("登录成功");
    }

    @Override
    public SysUser getSysUserById(int userId){
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
        return sysUser;
    }

    @Override
    public SysUserVo detail(int userId) {
        SysUserVo sysUser = sysUserMapper.selectUserDetailByUserId(userId);
        return sysUser;
    }

    @Override
    public void updateCurrentUserIp(SysUser user, String ip){
        user.setUserLastLoginIp(ip);
        sysUserMapper.updateIpByPrimary(user);
    }

    @Override
    public PageInfo getUserListByKeyword(int pageNum, int pageSize, String searchUser) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUserVo> sysUserVoList = sysUserMapper.selectUserByConditions(searchUser);
        PageInfo pageResult = new PageInfo(sysUserVoList);
        pageResult.setList(sysUserVoList);
        return pageResult;
    }

    @Override
    public ServerResponse checkMobile(String mobile) {
        return null;
    }

    @Override
    public ServerResponse<SysUser> save(SysUserParam sysUserParam) {
        return null;
    }

    @Override
    public ServerResponse updateDeleteSysUserById(int id) {
        return null;
    }

    @Override
    public ServerResponse updateStatusSysUserById(int id) {
        return null;
    }

    @Override
    public ServerResponse update(SysUserParam sysUserParam) {
        return null;
    }
}
